package com.ailink.learningrabbitmq.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.80.130");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

//        String queueName = "queue.direct";
//        String exchangeName = "exchange.direct";
//        String routingKey = "routing.direct";
//        channel.exchangeDeclare(exchangeName, "direct", true, false, false, null);
//        channel.queueDeclare(queueName, true, false, false, null);
//        channel.queueBind(queueName, exchangeName, routingKey);

//        String queueName = "queue.topic";
//        String exchangeName = "exchange.topic";
//        String routingKey = "user.#";
//        channel.exchangeDeclare(exchangeName, "topic", false, false, false, null);
//        channel.queueDeclare(queueName, false, false, false, null);
//        channel.queueBind(queueName, exchangeName, routingKey);


        String queueName = "queue.fanout";
        String exchangeName = "exchange.fanout";
        String routingKey = "";
        channel.exchangeDeclare(exchangeName, "fanout", false, false, false, null);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

//        DefaultConsumer defaultConsumer = new DefaultConsumer(channel);
        channel.basicConsume(queueName, true,  new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException
            {
                String routingKey = envelope.getRoutingKey();
                String contentType = properties.getContentType();
                long deliveryTag = envelope.getDeliveryTag();
                // (process the message components here ...)

                System.out.println(new String(body));
                channel.basicAck(deliveryTag, false);
            }
        });

    }
}
